package org.md.budzik.gui;

import java.util.Date;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.ToggleButton;

import org.md.budzik.*;

/**
 * Aktywność pozwalająca użytkownikowi
 * ustawić budzik na zadaną godzinę
 * @author Saephir
 *
 */
public class MDBudzikActivity extends Activity {
	
	private ToggleButton button;
	private TimePicker timePicker;
	
	private PendingIntent pendingIntent;
	
	public static final int WAKEUP_CODE = 82377;
	public static final String PREFS_NAME = "MDBudzikPrefs";
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        MDProblemActivity.setSettingsActivity(this);
        
        timePicker = (TimePicker)findViewById(R.id.timePicker1);
        timePicker.setIs24HourView(true);
        
        button = (ToggleButton)findViewById(R.id.toggleButton1);
        
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        button.setChecked(settings.getBoolean("switchOn", false));
        
        if(button.isChecked()) {
	        Date d = new Date();
	        timePicker.setCurrentHour(settings.getInt("hour", d.getHours()));
	        timePicker.setCurrentMinute(settings.getInt("minute", d.getMinutes()));
        }
        
        button.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				
				try {
				
					AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
				
					// Ustaw alarm
					if(isChecked)
					{
						
						int hour = timePicker.getCurrentHour();
						int minute = timePicker.getCurrentMinute();
						
						Date today = new Date();
						Date d = new Date();
						d.setHours(hour);
						d.setMinutes(minute);
						d.setSeconds(0);
						
						// Jeżeli nastawiamy godzinę <= od obecnej, to mamy na ogół
						// na myśli następny dzień.
						if(d.getHours() < today.getHours() || (d.getHours()) == today.getHours() &&
								d.getMinutes() <= today.getMinutes())
						{
							d.setTime(d.getTime()+24*60*60*1000);
						}
						
						Intent intent = new Intent(MDBudzikActivity.this, MDProblemActivity.class);
						pendingIntent = PendingIntent.getActivity(getApplicationContext(), WAKEUP_CODE, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
						alarmManager.set(AlarmManager.RTC_WAKEUP, d.getTime(), pendingIntent);
						Toast.makeText(getApplicationContext(), "Ustawiono budzik.", Toast.LENGTH_LONG).show();
						
					}
					// Odwołaj alarm
					else
					{
						if(pendingIntent != null) {
							alarmManager.cancel(pendingIntent);
						}
						else {
							Intent intent = new Intent(MDBudzikActivity.this, MDProblemActivity.class);
							pendingIntent = PendingIntent.getActivity(getApplicationContext(), WAKEUP_CODE, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
							alarmManager.cancel(pendingIntent);
						}
						
						Toast.makeText(getApplicationContext(), "Wyłączono budzik.", Toast.LENGTH_LONG).show();
					}
				
				}
				catch(Exception exc) {
					exc.printStackTrace();
				}
			}
		});
        
        if(MDProblemActivity.isMusicPlaying())
        {
        	finish();
        	startActivity(new Intent(MDBudzikActivity.this, MDProblemActivity.class));
        }
        
    }
    
    @Override
    protected void onSaveInstanceState(Bundle outState) {
    	super.onSaveInstanceState(outState);
    	outState.putBoolean("switchOn", button.isSelected());
    	int hour = timePicker.getCurrentHour();
		int minute = timePicker.getCurrentMinute();
		outState.putInt("hour", hour);
		outState.putInt("minute", minute);
    }
    
    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
      	button.setSelected(savedInstanceState.getBoolean("switchOn"));
		timePicker.setCurrentHour(savedInstanceState.getInt("hour"));
		timePicker.setCurrentMinute(savedInstanceState.getInt("minute"));
    }
    
    @Override
    public void onStop() {
    	super.onStop();
    	SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
    	SharedPreferences.Editor editor = settings.edit();
    	editor.putBoolean("switchOn", button.isChecked());
    	editor.putInt("hour", timePicker.getCurrentHour());
    	editor.putInt("minute", timePicker.getCurrentMinute());
    	editor.commit();
    	MDProblemActivity.setSettingsActivity(null);
    }

    
}